import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import * as deviceApi from '../api/device'
import * as channelApi from '../api/channel'
import * as discoveryApi from '../api/discovery'

export const useDeviceStore = defineStore('device', () => {
  // State
  const devices = ref([])
  const channels = ref([])
  const discoveredDevices = ref([])
  const currentDevice = ref(null)
  const currentChannel = ref(null)

  const loading = ref({
    devices: false,
    channels: false,
    discovery: false,
    deviceDetail: false,
    channelDetail: false
  })

  const pagination = ref({
    current: 1,
    size: 10,
    total: 0
  })

  const filters = ref({
    keyword: '',
    status: '',
    manufacturer: '',
    enabled: null
  })

  const statistics = ref({
    totalDevices: 0,
    onlineDevices: 0,
    offlineDevices: 0,
    enabledDevices: 0,
    disabledDevices: 0,
    totalChannels: 0,
    activeChannels: 0
  })

  // Computed
  const onlineDevices = computed(() => devices.value.filter(device => device.status === 'ONLINE'))

  const offlineDevices = computed(() => devices.value.filter(device => device.status === 'OFFLINE'))

  const enabledDevices = computed(() => devices.value.filter(device => device.enabled))

  const activeChannels = computed(() =>
    channels.value.filter(channel => channel.status === 'ACTIVE')
  )

  const devicesByManufacturer = computed(() => {
    const grouped = {}
    devices.value.forEach(device => {
      const manufacturer = device.manufacturer || 'Unknown'
      if (!grouped[manufacturer]) {
        grouped[manufacturer] = []
      }
      grouped[manufacturer].push(device)
    })
    return grouped
  })

  // Actions
  const fetchDevices = async (params = {}) => {
    loading.value.devices = true
    try {
      const response = await deviceApi.getDevices({
        page: pagination.value.current - 1,
        size: pagination.value.size,
        sort: 'id',
        keyword: filters.value.keyword,
        ...params
      })

      devices.value = response.content || []
      pagination.value.total = response.totalElements || 0

      return response
    } catch (error) {
      console.error('Failed to fetch devices:', error)
      ElMessage.error('获取设备列表失败')
      throw error
    } finally {
      loading.value.devices = false
    }
  }

  const fetchAllDevices = async () => {
    loading.value.devices = true
    try {
      const response = await deviceApi.getAllDevices()
      devices.value = response || []
      return response
    } catch (error) {
      console.error('Failed to fetch all devices:', error)
      ElMessage.error('获取所有设备失败')
      throw error
    } finally {
      loading.value.devices = false
    }
  }

  const fetchDeviceById = async id => {
    loading.value.deviceDetail = true
    try {
      const response = await deviceApi.getDeviceById(id)
      currentDevice.value = response
      return response
    } catch (error) {
      console.error('Failed to fetch device:', error)
      ElMessage.error('获取设备详情失败')
      throw error
    } finally {
      loading.value.deviceDetail = false
    }
  }

  const addDevice = async deviceData => {
    try {
      const response = await deviceApi.addDevice(deviceData)
      devices.value.unshift(response)

      ElNotification({
        title: '成功',
        message: '设备添加成功',
        type: 'success'
      })

      // Refresh statistics
      await fetchStatistics()

      return response
    } catch (error) {
      console.error('Failed to add device:', error)
      ElMessage.error('添加设备失败')
      throw error
    }
  }

  const updateDevice = async (id, deviceData) => {
    try {
      const response = await deviceApi.updateDevice(id, deviceData)

      const index = devices.value.findIndex(device => device.id === id)
      if (index > -1) {
        devices.value[index] = response
      }

      if (currentDevice.value?.id === id) {
        currentDevice.value = response
      }

      ElMessage.success('设备更新成功')
      return response
    } catch (error) {
      console.error('Failed to update device:', error)
      ElMessage.error('更新设备失败')
      throw error
    }
  }

  const deleteDevice = async id => {
    try {
      await deviceApi.deleteDevice(id)

      const index = devices.value.findIndex(device => device.id === id)
      if (index > -1) {
        devices.value.splice(index, 1)
      }

      if (currentDevice.value?.id === id) {
        currentDevice.value = null
      }

      // Remove related channels
      channels.value = channels.value.filter(channel => channel.deviceId !== id)

      ElMessage.success('设备删除成功')

      // Refresh statistics
      await fetchStatistics()
    } catch (error) {
      console.error('Failed to delete device:', error)
      ElMessage.error('删除设备失败')
      throw error
    }
  }

  const toggleDeviceEnabled = async (id, enabled) => {
    try {
      const response = await deviceApi.toggleDeviceEnabled(id, { enabled })

      const index = devices.value.findIndex(device => device.id === id)
      if (index > -1) {
        devices.value[index] = response
      }

      if (currentDevice.value?.id === id) {
        currentDevice.value = response
      }

      ElMessage.success(`设备已${enabled ? '启用' : '禁用'}`)
      return response
    } catch (error) {
      console.error('Failed to toggle device:', error)
      ElMessage.error('切换设备状态失败')
      throw error
    }
  }

  const testDeviceConnection = async id => {
    try {
      const response = await deviceApi.testDeviceConnection(id)

      if (response.success) {
        ElMessage.success('设备连接正常')
      } else {
        ElMessage.warning('设备连接失败')
      }

      return response
    } catch (error) {
      console.error('Failed to test device connection:', error)
      ElMessage.error('测试连接失败')
      throw error
    }
  }

  const refreshDeviceInfo = async id => {
    try {
      const response = await deviceApi.refreshDeviceInfo(id)

      const index = devices.value.findIndex(device => device.id === id)
      if (index > -1) {
        devices.value[index] = response
      }

      if (currentDevice.value?.id === id) {
        currentDevice.value = response
      }

      ElMessage.success('设备信息刷新成功')
      return response
    } catch (error) {
      console.error('Failed to refresh device info:', error)
      ElMessage.error('刷新设备信息失败')
      throw error
    }
  }

  const fetchChannels = async () => {
    loading.value.channels = true
    try {
      const response = await channelApi.getAllChannels()
      channels.value = response || []
      return response
    } catch (error) {
      console.error('Failed to fetch channels:', error)
      ElMessage.error('获取通道列表失败')
      throw error
    } finally {
      loading.value.channels = false
    }
  }

  const fetchChannelsByDevice = async deviceId => {
    loading.value.channels = true
    try {
      // 根据deviceId类型选择合适的API方法
      const response = typeof deviceId === 'string' 
        ? await channelApi.getChannelsByDeviceIdString(deviceId)
        : await channelApi.getChannelsByDevice(deviceId)
      return response || []
    } catch (error) {
      console.error('Failed to fetch channels by device:', error)
      ElMessage.error('获取设备通道失败')
      throw error
    } finally {
      loading.value.channels = false
    }
  }

  const fetchChannelById = async id => {
    loading.value.channelDetail = true
    try {
      const response = await channelApi.getChannelById(id)
      currentChannel.value = response
      return response
    } catch (error) {
      console.error('Failed to fetch channel:', error)
      ElMessage.error('获取通道详情失败')
      throw error
    } finally {
      loading.value.channelDetail = false
    }
  }

  const discoverDevices = async () => {
    loading.value.discovery = true
    try {
      const response = await discoveryApi.discoverDevices()
      discoveredDevices.value = response || []

      ElNotification({
        title: '设备发现',
        message: `发现 ${response.length} 个设备`,
        type: 'info'
      })

      return response
    } catch (error) {
      console.error('Failed to discover devices:', error)
      ElMessage.error('设备发现失败')
      throw error
    } finally {
      loading.value.discovery = false
    }
  }

  const addDiscoveredDevice = async discoveredDevice => {
    try {
      const response = await discoveryApi.addDiscoveredDevice(discoveredDevice)
      devices.value.unshift(response)

      // Remove from discovered list
      const index = discoveredDevices.value.findIndex(
        d => d.ipAddress === discoveredDevice.ipAddress
      )
      if (index > -1) {
        discoveredDevices.value.splice(index, 1)
      }

      ElMessage.success('设备添加成功')
      return response
    } catch (error) {
      console.error('Failed to add discovered device:', error)
      ElMessage.error('添加发现的设备失败')
      throw error
    }
  }

  const fetchStatistics = async () => {
    try {
      const response = await deviceApi.getDeviceStatistics()
      statistics.value = response || {}
      return response
    } catch (error) {
      console.error('Failed to fetch statistics:', error)
      // Don't show error message for statistics
      throw error
    }
  }

  const checkDeviceStatus = async () => {
    // Periodically check device status
    try {
      await fetchStatistics()

      // Check for offline devices
      const offlineCount = statistics.value.offlineDevices || 0
      if (offlineCount > 0) {
        // Could add notification for offline devices
      }
    } catch (error) {
      console.warn('Failed to check device status:', error)
    }
  }

  const refreshDevices = async () => {
    await fetchDevices()
    await fetchStatistics()
  }

  const setFilters = newFilters => {
    Object.assign(filters.value, newFilters)
  }

  const setPagination = newPagination => {
    Object.assign(pagination.value, newPagination)
  }

  const clearCurrentDevice = () => {
    currentDevice.value = null
  }

  const clearCurrentChannel = () => {
    currentChannel.value = null
  }

  const clearDiscoveredDevices = () => {
    discoveredDevices.value = []
  }

  // 添加getStatistics方法作为fetchStatistics的别名
  const getStatistics = fetchStatistics

  return {
    // State
    devices,
    channels,
    discoveredDevices,
    currentDevice,
    currentChannel,
    loading,
    pagination,
    filters,
    statistics,

    // Computed
    onlineDevices,
    offlineDevices,
    enabledDevices,
    activeChannels,
    devicesByManufacturer,

    // Actions
    fetchDevices,
    fetchAllDevices,
    fetchDeviceById,
    addDevice,
    updateDevice,
    deleteDevice,
    toggleDeviceEnabled,
    testDeviceConnection,
    refreshDeviceInfo,
    fetchChannels,
    fetchChannelsByDevice,
    fetchChannelById,
    discoverDevices,
    addDiscoveredDevice,
    fetchStatistics,
    getStatistics,
    checkDeviceStatus,
    refreshDevices,
    setFilters,
    setPagination,
    clearCurrentDevice,
    clearCurrentChannel,
    clearDiscoveredDevices
  }
})
